package com.kalvan.web.servlet.filter;

import com.kalvan.web.servlet.request.RequestWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * 扩展支持request 修改
 * 需要实现init 和destroy 不然在tomcat8中会有问题
 *
 * @author chenliang
 */
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@ConditionalOnProperty(name = "kalvan.web.requestFilter.enabled", matchIfMissing = true)
@Component
@Slf4j
public class RequestFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        Map<String, String[]> params = new HashMap<>(request.getParameterMap());
        request = new RequestWrapper((HttpServletRequest) request, params);
        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("init RequestFilter...");
    }

    @Override
    public void destroy() {
        log.info("destroy RequestFilter");
    }
}